package ejb;

import java.util.List;

import javax.ejb.LocalBean;
import javax.ejb.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import model.Member;


@Singleton
@LocalBean
public class VoteCounter {
	private static final int MAX_MEMBERS =10;	
	@PersistenceContext
	private EntityManager em;
	
	private Member winner;
	private Member[] winners;
	
	public void winnerCalculator(){
		if(winners != null){
			return;
		}
		winners = new Member[MAX_MEMBERS];
		int winCount = 0;
		
		List<Member> members = (List<Member>)em.createNamedQuery("Member.findAll", Member.class).getResultList();
		Member[] ms = new Member[members.size()];
		ms = members.toArray(ms);
		
		int[] votes = new int[ms.length];
		
		for (int i = 0; i<ms.length;i++){
		votes[i] = ms[i].getVotes().size() + ms[i].getVotes().size() + ms[i].getVotes().size();
			
		}
		int max;
		int maxPos;
		for(int i = 0; i<MAX_MEMBERS; i++){
			max = -1;
			maxPos = -1;
			for(int j=0; j<votes.length;j++){
				if(votes[i] >max){
					max = votes[i];
					maxPos = j;
				}
				winners[winCount++]= ms[maxPos];
				votes[maxPos] = -1;
				}
			}
		}
	//public Vote getPartyChosen(String partyID);
	
	public Member getWinner(){
		return winner;
	}
	
	public Member[] getWinners(){
		return winners;
	}
	}
	

